from django.shortcuts import render
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from carts.utils import merge_cart_cookie_to_redis
from users.serializers import RegisterCreateUserSerializer, AddressSerializer, AddressTitleSerializer
from .models import User
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.permissions import IsAuthenticated
from .serializers import UserCenterInfoSerializer, EmailUpdateSerializer, UserHistorySerializer
from .serializers import SKUSerializer
from django_redis import get_redis_connection
from goods.models import SKU
# Create your views here.


# APIView
# GenericAPIView
# ListAPIView,CreateAPIView

class RegisterUserNameView(APIView):
    """
    GET    /users/usernames/(?P<username>\w{5,20})/count/
    
    
    POST   /users/usernames/              username = xxx
    GET    /users/usernames/?username=xxx
    """""

    def get(self, request, username):

        # 查询数据库,查看是否有指定的数据
        count = User.objects.filter(username=username).count()

        # count = 0 不存在
        # count >= 1 存在

        context = {
            'count': count,
            'username': username
        }

        return Response(context)


class RegisterMobileCountView(APIView):
    """
    GET    /users/phones/(?P<mobile>1[345789]\d{9})/count/
    """""

    def get(self, request, mobile):

        # 查询数据库,查看是否有指定数据
        count = User.objects.filter(mobile=mobile).count()

        # count = o 不存在
        # count >= 1 存在

        context = {
            'count': count,
            'phone': mobile
        }

        return Response(context)


# APIView
# GenericAPIView
# ListAPIView,CreateAPIView
class RegisterCreateUserView(CreateAPIView):
    """
    POST    /users/
    1.获取前端提交的数据 username,password,password2,mobile,sms_code,allow
    2.对提交的数据进行校验
    3.保存入库
    """""

    # 需求数据入库
    serializer_class = RegisterCreateUserSerializer


class UserCenterInfoView(RetrieveAPIView):
    """
    1.访问个人中心必须是登录用户,只能是认证用户
    2.得到指定用户的信息,用户信息是模型,模型转换为JSON
    """""
    # 必须是登录用户
    permission_classes = [IsAuthenticated]

    serializer_class = UserCenterInfoSerializer

    # 重写方法,返回用户模型
    def get_object(self):
       return self.request.user


"""
1.当用户点击设置邮箱的时候,让用户输入邮箱,输入邮箱之后,需要保存邮箱信息
2.我们需要发送一个激活邮件给用户
3.我们需要记录邮件的激活状态
4.如何发送邮件(邮件的url),和如何激活邮件
"""""


class EmailUpdateView(UpdateAPIView):
    """
    1.把用户的信息提交过来
    2.更新User的email字段就可以,需要对email进行校验
    """""

    permission_classes = [IsAuthenticated]

    serializer_class = EmailUpdateSerializer

    def get_object(self):
        return self.request.user


class VerifyEmailView(APIView):
    """
    GET     /users/emails/verifications?token=xxx
    GET     /users/emails/token/
    1.通过get发送将token返回回来
    2.获取token,检测token
    3.得到user.id,根据userid修改状态
    """""
    def get(self, request):
        # 1.通过get发送将token返回回来
        token = request.query_params.get('token')
        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 2.获取token,检测token,并得到userid根据userid返回用户模型
        user = User.user_by_token(token)

        # 3.得到user.id,根据userid修改状态
        # user = User.objects.get(id=id)
        if not user:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()

        return Response({'message': 'ok'})


class UserHistoryView(GenericAPIView):
    """
    1.只记录登录用户的历史记录,没有登录的用户是不能访问该接口的
    2.前端发送一个请求,这个请求要有用户信息和商品id
    3.判断商品id是否正确
    4.将记录信息保存在redis中

    POST  /users/browerhistories/
    """""
    # 添加权限
    permission_classes = [IsAuthenticated]

    serializer_class = UserHistorySerializer

    def post(self, request):

        # 1.创建序列化器,对数据进行校验
        serializer = self.get_serializer(data=request.data, context={'request': request})

        serializer.is_valid(raise_exception=True)

        serializer.save()

        return Response({'message': 'ok'})

    def get(self, request):
        """
        1.既然是用户的历史记录,肯定是登录用户
        2.用户的历史记录在redis中,从redis中获取数据
        3.根据id查询商品信息
        4.将模型转换为JSON
        """""
        user = request.user
        # 1.连接redis
        redis_conn = get_redis_connection('history')
        # 2.获取指定用户的历史记录
        ids = redis_conn.lrange('history_%s' % user.id, 0, 5)
        # 3.定义一个列表来接收查询好的数据
        skus = []
        for id in ids:
            sku = SKU.objects.get(pk=id)
            skus.append(sku)

        # 4.将模型转换为JSON
        serializer =  SKUSerializer(skus, many=True)

        return Response(serializer.data)


class UserAuthorizationView(ObtainJSONWebToken):

    def post(self, request):
        # 调用jwt扩展的方法，对用户登录的数据进行验证
        response = super().post(request)

        # 如果用户登录成功，进行购物车数据合并
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            # 表示用户登录成功
            user = serializer.validated_data.get("user")
            # 合并购物车
            # merge_cart_cookie_to_redis(request, user, response)
            response = merge_cart_cookie_to_redis(request, user, response)

        return response


class AddressViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):
    """
    用户地址新增与修改
    list GET: /users/addresses/
    create POST: /users/addresses/
    destroy DELETE: /users/addresses/
    action PUT: /users/addresses/pk/status/
    action PUT: /users/addresses/pk/title/
    """

    # 制定序列化器
    serializer_class = AddressSerializer
    # 添加用户权限
    permission_classes = [IsAuthenticated]
    # 由于用户的地址有存在删除的状态,所以我们需要对数据进行筛选

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        count = request.user.addresses.count()
        if count >= 20:
            return Response({'message':'保存地址数量已经达到上限'},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)

    def list(self, request, *args, **kwargs):
        """
        获取用户地址列表
        """""
        # 获取所有地址
        queryset = self.get_queryset()
        # 创建序列化器
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        # 响应
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': 20,
            'addresses': serializer.data,
        })

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """""
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """""
        address = self.get_object()
        serializer = AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """""
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)